<?php include_once"Server.php";?>
<?php include_once"Eventlog.php";?>
<?php
class Session extends PDO {
	 
	protected $db;
	 
	public function __construct() {
		$database = Server::getGeneralDatabaseName();
		$user = Server::getGeneralUser();
		$password = Server::getGeneralPassword();
		try {
			$this->db = new PDO($database, $user, $password);
			Eventlog::writeEventlog("Connected to database");
		} catch (PDOException $e) {
			Eventlog::writeEventlog($e->getMessage());
		}
	}
	 
	public function __destruct() {
		$this->db = null;
		Eventlog::writeEventlog("Disconnected from database");
	}
	 
	public function login($email, $password){
		try {
			/*$sql = "SELECT * FROM `user` WHERE `email` = :email AND `password` = :password;";*/
			$sql = "CALL getUser(:email, :password)";
			$stmt = $this->db->prepare($sql);
			$stmt->bindParam(":email", $email);
			$stmt->bindParam(":password", $password);
			$stmt->execute();
			if (sizeof($stmt->fetchAll()) == 0) {
				Eventlog::writeEventlog("Login not found!");
				return 0;//registration required
			} else {
				Eventlog::writeEventlog("Logindata correct!");
				return 1;//login code correct
			}
		} catch (PDOException $e) {
			Eventlog::writeEventlog($e->getMessage());
		}
	}
	
	public function register($email, $name, $password) {
		try {
			/*$sql = "SELECT * FROM `user` WHERE `email` = :email AND `password` = :password;";*/
			$sql = "SELECT createUser(:email, :name, :password)";
			$stmt = $this->db->prepare($sql);
			$stmt->bindParam(":email", $email);
			$stmt->bindParam(":password", $password);
			$stmt->bindParam(":name", $name);
			$stmt->execute();
			$result = $stmt->fetch();
			switch ($result[0]){
				case 0:
					Eventlog::writeEventlog("User Creation unsuccessful ");
					break;
				case 1:
					Eventlog::writeEventlog("User Creation successful ");
					break;
				default:
					Eventlog::writeEventlog("User Creation something went totally wrong ");
			}
		} catch (PDOException $e) {
			Eventlog::writeEventlog($e->getMessage());
		}
	}
	 
}
?>